package com.zhanglifan.action;

import com.opensymphony.xwork2.ModelDriven;
import com.zhanglifan.domain.Dept;
import com.zhanglifan.service.DeptService;
import com.zhanglifan.util.Page;

import java.util.ArrayList;
import java.util.List;

public class DeptAction extends BaseAction implements ModelDriven<Dept> {

    private DeptService deptService;

    private Dept dept = new Dept();

    private Page page = new Page();

    public Page getPage() {
        return page;
    }

    public void setDeptService(DeptService deptService) {
        this.deptService = deptService;
    }

    public String list(){
        page.setUrl("deptAction_list");
        deptService.findPage("from Dept where state=1",page,Dept.class,null);
        super.push(page);
        return "listSuccess";
    }

    public String toview(){
        super.push(deptService.get(Dept.class,dept.getId()));
        return "viewSuccess";
    }

    public String tocreate(){
        List<Dept> depts = deptService.find("from Dept where state=1", Dept.class, null);
        super.put("deptList",depts);
        return "toCreateSuccess";
    }

    public String insert(){
        dept.setState(1);
        deptService.saveOrUpdate(dept);
        return "insertSuccess";
    }

    public String toupdate(){
        List<Dept> depts = deptService.find("from Dept where state=1", Dept.class, null);
        List<Dept> ds = new ArrayList<>();
        deptService.getList(dept.getId(),ds);
        System.out.println("*** ds 的值是: " + ds + " ***");
        depts.removeAll(ds);
        super.put("deptList",depts);
        super.push(deptService.get(Dept.class,dept.getId()));
        return "toUpdateSuccess";
    }

    public String update(){
        Dept d = deptService.get(Dept.class,dept.getId());
        Dept p = deptService.get(Dept.class,dept.getParent().getId());
        d.setParent(p);
        d.setDeptName(dept.getDeptName());
        deptService.saveOrUpdate(d);
        return "updateSuccess";
    }

    public String delete(){
        deptService.deleteById(Dept.class,dept.getId());
        return "deleteSuccess";
    }

    @Override
    public Dept getModel() {
        return dept;
    }

}
